package com.qf.drbackend.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.qf.drbackend.consts.PayConst;
import com.qf.drbackend.pojos.Orders;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class PayUtils {

    public static void pay(String natGo,HttpServletResponse resp, Orders orders) throws IOException, AlipayApiException {
        //正式环境的支付网关： https://openapi.alipay.com/gateway.do
        //沙箱环境的支付网关：https://openapi.alipaydev.com/gateway.do
        AlipayClient alipayClient = new DefaultAlipayClient(PayConst.GATEWAY,
                PayConst.APP_ID,
                PayConst.APP_PRIVATE_KEY,
                "json",
                //支付宝默认处理数据时，都是采用的utf-8（这里如果使用的是gbk，中文到支付宝后就乱码了）
                "UTF-8",
                PayConst.ALIPAY_PUBLIC_KEY
                ,"RSA2");

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(natGo + PayConst.ASYNC_NOTIFY_URL);
        //同步跳转地址，仅支持http/https
        request.setReturnUrl(natGo + PayConst.SYNC_NOTIFY_URL);
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", orders.getId());
        //支付金额，最小值0.01元
        bizContent.put("total_amount", orders.getAmount());
        //订单标题，不可使用特殊符号
        bizContent.put("subject", "千锋餐厅："+orders.getId());
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        /******可选参数******/
        //bizContent.put("time_expire", "2022-08-01 22:00:00");

        //// 商品明细信息，按需传入 (一般传递订单项数据)
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");

            String body = response.getBody();

            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write(body);
        } else {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("支付失败");
        }
    }
}
